package cn.fu.security.des;

import java.security.Key;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 * @Title: MyDES.java
 * @Package cn.fu.security.des
 * @Description: 对称加密，des现在被aes替代（被破解）。而des却是标准
 * @author zhangxiaofu
 * @Company www.viewhigh.com
 * @date 2016年8月21日 下午2:55:07
 * @version V1.0
 */
public class MyDES {
	private static String src = "99fu";

	public static void main(String[] args) {
		bcDES();
	}

	public static void bcDES() {
try {
	Security.addProvider(new BouncyCastleProvider());
	//生成key
	KeyGenerator keyGenerator = KeyGenerator.getInstance("DES","BC");
//	KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");//默认为SunJCE version 1.7
	System.err.println(keyGenerator.getProvider());
	keyGenerator.init(56);//长度56或64
	SecretKey secretKey = keyGenerator.generateKey();
	byte[] bytesKey = secretKey.getEncoded();
	
	//key转换
	DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
	SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
	Key convertSecretKey = factory.generateSecret(desKeySpec);
	
	//加密
	Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
	cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
	byte [] result= cipher.doFinal(src.getBytes());
	System.err.println("bcDES encrypt:" +Hex.encodeHexString(result));
	
	//解密
	cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
	result = cipher.doFinal(result);
	System.err.println("bcDES decrypt:"+new String(result));
} catch (Exception e) {
	// TODO: handle exception
}
	}

	public static void ccDES() {

	}
}
